# 需求获取 获取kfc门店地址，并存放在数据库
import urllib.parse
import urllib.request


def send_post(page):
    url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
    data = {
        'cname': '成都',
        'pageIndex': page,
        'pageSize': 10
    }
    data = urllib.parse.urlencode(data).encode('utf-8')
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
    }
    request = urllib.request.Request(url=url, data=data, headers=headers)
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


def save_file(page, content):
    with open('kfc_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        fp.write(content)


def save_mysql(content):
    print('保存数据开始%s:' + content)
    print('保存数据结束')


if __name__ == '__main__':
    start_page = int(input('请输入开始页码:'))
    end_page = int(input('请输入结束页码:'))
    for page in range(start_page, end_page + 1):
        print('第%s页数据开始下载' % page)
        # 1.分页下载数据
        content = send_post(page)
        # 2.保存到文件
        save_file(page, content)
        # 3.保存到数据
        save_mysql(content)
    print('测试完成')
